import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Row, Col, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { history } from 'umi';
import {
  DrawerForm,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProFormSelect,
} from '@ant-design/pro-form';
import { useRequest } from 'umi';
import { Form } from 'antd';
import { del, fakeSubmitForm, list } from './service';

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */

const TableList: React.FC = () => {
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: () => {
      message.success('提交成功');
    },
  });

  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  const remove = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    try {
      const response = await del({ key: record.id });
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current?.reloadAndRest?.();
    } catch (error) {
      console.log(error);
      hide();
      message.error('处理失败');
      return false;
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: '科普名称',
      dataIndex: 'articleTitle',
    },
    // {
    //   title: '文章id',
    //   dataIndex: 'articleId',
    //   hideInSearch: true,
    // },
    // {
    //   title: '顺序',
    //   dataIndex: 'sortOrder',
    //   hideInSearch: true,
    // },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text, _, index) => {
        if (text == 0) return '正常';
        else return '下架';
      },
      hideInSearch: true,
    },
    {
      title: '发布日期',
      hideInForm: true,
      dataIndex: 'noticeTime',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            history.push(
              '/publish/sciencedetail?id=' + record.articleId + '&scienceId=' + record.id,
            );
          }}
        >
          编辑
        </a>,
        <Popconfirm title="是否要删除此条数据吗？" onConfirm={() => remove(record)}>
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const [form] = Form.useForm<{ name: string; company: string }>();

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'健康科普'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          sessionStorage.getItem(`hospitalStatus`) == 1 ||
          sessionStorage.getItem(`hospitalStatus`) == 3 ? (
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                history.push('/publish/sciencedetail');
              }}
            >
              <PlusOutlined />
              发布科普
            </Button>
          ) : null,
        ]}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          // console.log(params, sorter, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          let query = {
            likeQuery: {
              article_title: params.articleTitle,
            },
            eqQuery: {
              articleType: 2,
              hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
            },
            pageNum: params.current,
            pageSize: params.pageSize,
          };
          const msg = await list(query);
          if (msg.code == 200) {
            return {
              data: msg.data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: msg.message,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      <DrawerForm<{
        name: string;
        company: string;
      }>
        title="医院信息"
        form={form}
        visible={showDetail}
        onVisibleChange={setShowDetail}
        // layout="horizontal"
        autoFocusFirstInput
        drawerProps={{
          destroyOnClose: true,
        }}
        // {...formItemLayout}
        submitTimeout={2000}
        onFinish={async (values) => {
          console.log(values.name);
          message.success('提交成功');
          // 不返回不会关闭弹框
          return true;
        }}
      >
        <Row gutter={16}>
          <Col lg={10} md={12} sm={24}>
            <ProFormText
              width="md"
              label="医院全名"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入医院全名',
                },
              ]}
              placeholder="请输入医院全名"
            />
          </Col>
          <Col xl={{ span: 10, offset: 2 }} lg={{ span: 10 }} md={{ span: 12 }} sm={24}>
            <ProFormText
              width="md"
              label="医院名称"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入医院名称',
                },
              ]}
              placeholder="请输入医院名称"
            />
          </Col>
        </Row>
        <ProFormText
          width="xl"
          label="地址"
          name="title"
          rules={[
            {
              required: true,
              message: '请输入地址',
            },
          ]}
          placeholder="请输入地址"
        />
        <ProFormTextArea
          label="简介"
          width="xl"
          name="goal"
          rules={[
            {
              required: true,
              message: '请输入简介',
            },
          ]}
          placeholder="请输入简介"
        />
        <ProFormSelect
          width="xl"
          label="专业性质"
          name="publicUsers"
          fieldProps={{
            style: {
              margin: '8px 0',
            },
            mode: 'multiple',
          }}
          options={[
            {
              value: '1',
              label: '综合医院',
            },
            {
              value: '2',
              label: '专科医院',
            },
            {
              value: '3',
              label: '企业医院',
            },
          ]}
        />
        <Row gutter={16}>
          <Col lg={10} md={12} sm={24}>
            <ProFormDateRangePicker
              label="门诊时间"
              width="md"
              name="date"
              rules={[
                {
                  required: true,
                  message: '请选择起止时间',
                },
              ]}
              placeholder={['开始时间', '结束时间']}
            />
          </Col>
          <Col xl={{ span: 10, offset: 2 }} lg={{ span: 10 }} md={{ span: 12 }} sm={24}>
            <ProFormRadio.Group
              radioType="button"
              options={[
                {
                  value: '1',
                  label: '一甲',
                },
                {
                  value: '2',
                  label: '二甲',
                },
                {
                  value: '3',
                  label: '三甲',
                },
              ]}
              label="医院等级"
              name="publicType"
              fieldProps={{
                buttonStyle: 'solid',
              }}
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col lg={10} md={12} sm={24}>
            <ProFormRadio.Group
              options={[
                {
                  value: '1',
                  label: '是',
                },
                {
                  value: '2',
                  label: '否',
                },
              ]}
              label="是否分院"
              name="publicType"
            />
          </Col>
          <Col xl={{ span: 10, offset: 2 }} lg={{ span: 10 }} md={{ span: 12 }} sm={24}>
            <ProFormRadio.Group
              options={[
                {
                  value: '1',
                  label: '公立',
                },
                {
                  value: '2',
                  label: '民营',
                },
              ]}
              label="运营性质"
              name="publicType"
            />
          </Col>
        </Row>

        <Row gutter={16}>
          <Col lg={10} md={12} sm={24}>
            <ProFormRadio.Group
              options={[
                {
                  value: '1',
                  label: '启用',
                },
                {
                  value: '2',
                  label: '禁用',
                },
              ]}
              label="数据状态"
              name="publicType"
            />
          </Col>
          <Col xl={{ span: 10, offset: 2 }} lg={{ span: 10 }} md={{ span: 12 }} sm={24}>
            <ProFormRadio.Group
              options={[
                {
                  value: '1',
                  label: '营业',
                },
                {
                  value: '2',
                  label: '歇业',
                },
              ]}
              label="营业状态"
              name="publicType"
            />
          </Col>
        </Row>
      </DrawerForm>

      {/* <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProForm
            hideRequiredMark
            {...formItemLayout}
            style={{ margin: 'auto', marginTop: 8, maxWidth: 600 }}
            name="basic"
            layout="horizontal"
            initialValues={{}}
            onFinish={onFinish}
          >
           
          
          
           
          </ProForm>
        )}
      </Drawer> */}
    </PageContainer>
  );
};

export default TableList;
